package com.dmyang.service.impl;

import com.dmyang.common.pojo.HyResult;
import com.dmyang.dao.HyMessageMapper;
import com.dmyang.entity.HyMessage;
import com.dmyang.entity.HyMessageExample;
import com.dmyang.service.MessageService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.HashMap;
import java.util.Map;

/**
 * 留言表Service
 * Created by brss on 2017/8/9.
 */
@Service("messageServiceImpl")
public class MessageServiceImpl implements MessageService {

    @Autowired
    private HyMessageMapper messageMapper;

    /**
     *  查询出留言列表
     * @param pageSize 每页条数
     * @param page 第几页
     * @return  需要返回的是：totalPages,List<HyMessage>
     *     所以决定返回Map
     */
    @Transactional
    @Override
    public Map<?,?> showMessageList(Integer pageSize, Integer page) {
        Map map = new HashMap<>();
        //分页
        PageHelper.startPage(page,pageSize);
        //查询
        HyMessageExample example = new HyMessageExample();
        HyMessageExample.Criteria criteria = example.createCriteria();
        List<HyMessage> list = messageMapper.selectByExample(example);
        //获取总结果数
        PageInfo<HyMessage> info = new PageInfo<>(list);
        Long totalPage = 0L;
        if(info.getTotal()%pageSize==0){
            totalPage=info.getTotal()/pageSize;
        }else {
            totalPage=(info.getTotal()/pageSize)+1;
        }
        map.put("totalPages",totalPage);
        map.put("result",list);
        return map;
    }

    /**
     * 插入一条留言
     * @param message
     * @return
     * @throws Exception
     */
    @Transactional
    @Override
    public HyResult addMessage(HyMessage message) throws Exception {

        messageMapper.insertSelective(message);
        return HyResult.build(200,"插入成功！");
    }
}
